﻿using BW.WMS.WareHouseStatistics;
using BW.WMS.WareHouseStatistics.Statistics;
using BW.WMS.WareHouseStatistics.StockManagement;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;

namespace BW.WMS.Controllers
{
    [Route("api/app/stock-management")]
    [ApiController]
    public class StockManagementController : AbpController
    {
        private readonly IRepository<StockManagementModel> _stockManagementRepository;
        private readonly IStockManagementAppService _stockManagementAppService;

        public StockManagementController(IRepository<StockManagementModel> stockManagementRepository, IStockManagementAppService stockManagementAppService)
        {
            _stockManagementRepository = stockManagementRepository;
            _stockManagementAppService = stockManagementAppService;
        }

        [HttpGet("inbound-category-data")]
        public async Task<ActionResult<object>> GetInboundCategoryData()
        {
            try
            {
                // 先获取IQueryable
                var queryable = await _stockManagementRepository.GetQueryableAsync();

                // 查询入库数据，按入库类型(Stocktype)分组
                var inboundByCategory = await queryable
                    .Where(s => !s.IsDeleted && s.Stocktype != null) // 排除已删除和类型为空的记录
                    .GroupBy(s => s.Stocktype)
                    .Select(g => new {
                        Category = g.Key,
                        Count = g.Count(), // 入库单数量
                        TotalQuantity = g.Sum(s => s.Stocknumber ?? 0), // 总入库数量
                        TotalAmount = g.Sum(s => s.Stockmoney ?? 0) // 总入库金额
                    })
                    .OrderByDescending(x => x.TotalQuantity) // 按数量排序
                    .ToListAsync();

                // 如果没有数据，返回空数据
                if (!inboundByCategory.Any())
                {
                    return Ok(new
                    {
                        Categories = new string[0],
                        Counts = new int[0],
                        Quantities = new int[0],
                        Amounts = new decimal[0]
                    });
                }

                return Ok(new
                {
                    Categories = inboundByCategory.Select(c => c.Category).ToArray(),
                    Counts = inboundByCategory.Select(c => c.Count).ToArray(), // 入库单数量
                    Quantities = inboundByCategory.Select(c => c.TotalQuantity).ToArray(), // 入库总数量
                    Amounts = inboundByCategory.Select(c => c.TotalAmount).ToArray() // 入库总金额
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"获取入库分类数据时出错: {ex.Message}");
            }
        }

        [HttpGet("recent-inbound-stats")]
        public async Task<ActionResult<object>> GetRecentInboundStats()
        {
            try
            {
                var queryable = await _stockManagementRepository.GetQueryableAsync();
                var startDate = DateTime.Now.AddMonths(-6);

                // 按月份统计入库数据
                var monthlyStats = await queryable
                    .Where(s => !s.IsDeleted && s.Stocktime >= startDate)
                    .GroupBy(s => new { s.Stocktime.Year, s.Stocktime.Month })
                    .OrderBy(g => g.Key.Year).ThenBy(g => g.Key.Month)
                    .Select(g => new {
                        Date = $"{g.Key.Year}-{g.Key.Month:D2}",
                        Count = g.Count(),
                        TotalQuantity = g.Sum(s => s.Stocknumber ?? 0),
                        TotalAmount = g.Sum(s => s.Stockmoney ?? 0)
                    })
                    .ToListAsync();

                return Ok(new
                {
                    Dates = monthlyStats.Select(s => s.Date).ToArray(),
                    Counts = monthlyStats.Select(s => s.Count).ToArray(),
                    Quantities = monthlyStats.Select(s => s.TotalQuantity).ToArray(),
                    Amounts = monthlyStats.Select(s => s.TotalAmount).ToArray()
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"获取入库统计数据时出错: {ex.Message}");
            }
        }


        // 获取操作统计信息
        [HttpGet("operation-statistics")]
        public async Task<ActionResult<object>> GetOperationStatistics()
        {
            try
            {
                var queryable = await _stockManagementRepository.GetQueryableAsync();
                var today = DateTime.Today;
                var thisWeek = today.AddDays(-(int)today.DayOfWeek);
                var thisMonth = new DateTime(today.Year, today.Month, 1);

                // 今日统计
                var todayStats = await queryable
                    .Where(s => !s.IsDeleted && s.CreationTime.Date == today)
                    .GroupBy(s => 1)
                    .Select(g => new {
                        Count = g.Count(),
                        TotalQuantity = g.Sum(s => s.Stocknumber ?? 0),
                        TotalAmount = g.Sum(s => s.Stockmoney ?? 0)
                    })
                    .FirstOrDefaultAsync();

                // 本周统计
                var weekStats = await queryable
                    .Where(s => !s.IsDeleted && s.CreationTime >= thisWeek)
                    .GroupBy(s => 1)
                    .Select(g => new {
                        Count = g.Count(),
                        TotalQuantity = g.Sum(s => s.Stocknumber ?? 0),
                        TotalAmount = g.Sum(s => s.Stockmoney ?? 0)
                    })
                    .FirstOrDefaultAsync();

                // 本月统计
                var monthStats = await queryable
                    .Where(s => !s.IsDeleted && s.CreationTime >= thisMonth)
                    .GroupBy(s => 1)
                    .Select(g => new {
                        Count = g.Count(),
                        TotalQuantity = g.Sum(s => s.Stocknumber ?? 0),
                        TotalAmount = g.Sum(s => s.Stockmoney ?? 0)
                    })
                    .FirstOrDefaultAsync();

                return Ok(new
                {
                    Today = todayStats ?? new { Count = 0, TotalQuantity = 0, TotalAmount = 0m },
                    ThisWeek = weekStats ?? new { Count = 0, TotalQuantity = 0, TotalAmount = 0m },
                    ThisMonth = monthStats ?? new { Count = 0, TotalQuantity = 0, TotalAmount = 0m },
                    GeneratedAt = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"获取操作统计信息时出错: {ex.Message}");
            }
        }

        [HttpGet("operation-logs")]
        public async Task<ActionResult<object>> GetOperationLogs(
    int limit = 20,
    string? operationType = null,
    string? status = null)
        {
            try
            {
                var queryable = await _stockManagementRepository.GetQueryableAsync();

                // 构建查询条件
                var query = queryable.Where(s => !s.IsDeleted);

                // 按操作类型筛选
                if (!string.IsNullOrEmpty(operationType))
                {
                    query = query.Where(s => s.Stocktype == operationType);
                }

                // 按状态筛选
                if (!string.IsNullOrEmpty(status))
                {
                    query = query.Where(s => s.Stockstate == status);
                }

                var operationLogs = await query
                    .OrderByDescending(s => s.CreationTime)
                    .Take(limit)
                    .Select(s => new {
                        Id = s.Id,
                        StockCode = s.Stockcode,
                        OperationType = s.Stocktype,
                        GoodsInfo = new
                        {
                            Code = s.Goodscode,
                            Type = s.Goodstype,
                            Version = s.Version,
                            Unit = s.Unit
                        },
                        Quantities = new
                        {
                            Stock = s.Stocknumber ?? 0,
                            Current = s.Newnumber ?? 0,
                            Allocation = s.Allocationnumber ?? 0
                        },
                        Financial = new
                        {
                            Amount = s.Stockmoney ?? 0
                        },
                        Personnel = new
                        {
                            Agent = s.Agent,
                            Creator = s.Creator,
                            Phone = s.Phone
                        },
                        Status = s.Stockstate,
                        Timestamps = new
                        {
                            OperationTime = s.Stocktime,
                            CreationTime = s.CreationTime,
                            LastModificationTime = s.LastModificationTime
                        },
                        Description = s.Stockdesc,
                        StateDescription = s.Statedesc
                    })
                    .ToListAsync();

                return Ok(new
                {
                    TotalCount = operationLogs.Count,
                    Filters = new
                    {
                        OperationType = operationType,
                        Status = status,
                        Limit = limit
                    },
                    Logs = operationLogs
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"获取操作日志时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet("export-data")]
        public async Task<IActionResult> ExportDataAsync([FromQuery] StockManagementGetList filter)
        {
            var bytes = await _stockManagementAppService.ExportDataAsync(filter);
            var fileName = $"入库统计_{DateTime.Now:yyyyMMddHHmmss}.xlsx";

            return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }


    }
}